<?php

namespace app\logic\traits;

trait ExcelTraits
{
    /**
     * excel表格导出
     * @param string $fileName 文件名称
     * @param array $headArr 表头名称
     * @param array $data 要导出的数据
     * @author static7
     */
    private function excelExport($fileName = '', $headArr = [], $data = [])
    {
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties();
        $keyA = ord("A"); // 设置表头
        foreach ($headArr as $v) {
            $colum = chr($keyA);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $keyA += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        foreach ($data as $key => $rows) { // 行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) { // 列写入
                //判断数据是否有数组，如果有数组，转换成字符串
                if (is_array($value)) {
                    $value = implode("、", $value);
                }
                $objActSheet->setCellValue(chr($span) . $column, $value);
                $span++;
            }
            $column++;
        }
        $fileName .= "_" . date("Y_m_d", time()) . ".xls";
        //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
        //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表

        $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=" . $fileName);
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output'); // 文件通过浏览器下载
        exit();
    }
}